package bin_tree.leetcode;


import java.util.LinkedList;
import java.util.Queue;

/**
 * 对称二叉树
 */
public class Num101 {
//    public boolean isSymmetric(TreeNode root) {
//        if (root == null) {
//            return true;
//        }
//        // root.left和root.right是否互为镜像
//        return isMirror(root.left,root.right);
//    }

    /**
     * 判断传入的两棵树是否互为镜像关系
     * @param left
     * @param right
     * @return
     */
    private boolean isMirror(TreeNode left, TreeNode right) {
        if (left == null && right == null) {
            return true;
        }
        if (left == null || right == null) {
            return false;
        }
        if (left.val != right.val) {
            return false;
        }
        // 判断left.left和right.right是否相同 &&
        // 判断left.right 和 right.left是否相同
        return isMirror(left.left,right.right) &&
                isMirror(left.right,right.left);
    }
    // 队列实现
    public boolean isSymmetric(TreeNode root) {
        if(root == null || (root.left == null && root.right == null)) {
            return true;
        }
        // 使用队列存储每一层需要判断对称的节点
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root.left);
        queue.offer(root.right);
        while (!queue.isEmpty()) {
            // 每次取出一组元素(左树和右树的根)
            TreeNode left = queue.poll();
            TreeNode right = queue.poll();
            // 判空
            if (left == null && right == null) {
                continue;
            }
            if (left == null || right == null) {
                return false;
            }
            if (left.val != right.val) {
                return false;
            }
            // 当前左右树的根节点判断完毕，将left.left和right.right入队
            // 将left.right和right.left入队
            queue.offer(left.left);
            queue.offer(right.right);

            queue.offer(left.right);
            queue.offer(right.left);
        }
        return true;
    }

}
